<script lang="ts">
    import { useClassList } from "../utils/useClassList";
    import { useStyle } from "../utils/useStyle";
    import { isColor } from "../utils/utils";
    import type { BadgeProps } from "./Badge";

    const props: BadgeProps = $props();
    const overflowCount = props.overflowCount ?? 99;

    const classList = $derived(
        useClassList(props, "cm-badge", {
            "cm-badge-status": props.status,
        })
    );

    const styles = $derived.by(() => {
        const style: any = {};
        if (props.offset && props.offset.length === 2) {
            style["margin-top"] = `${props.offset[0]}px`;
            style["margin-right"] = `${props.offset[1]}px`;
        }
        return useStyle(props, style);
    });

    const showCount = $derived(props.count && props.count > overflowCount ? Math.min(overflowCount, props.count) + "+" : props.count);

    const statusClass = $derived({
        "cm-badge-status-dot": true,
        [`cm-badge-status-${props.status}`]: !!props.status,
        [`cm-badge-status-${props.color}`]: !!props.color && props.color.indexOf("#") === -1,
    });

    const statusStyle = $derived(
        useStyle(
            {},
            {
                "background-color": props.color && isColor(props.color) ? props.color : "",
            }
        )
    );

    const countClass = $derived({
        "cm-badge-count": true,
        [`cm-badge-count-${props.type}`]: !!props.type,
    });
</script>

<span class={classList}>
    {@render props.children?.()}
    {#if !props.status && !props.color}
        {#if props.count !== undefined || props.text !== undefined}
            <sup class={countClass} style={styles}>{showCount}{props.text}</sup>
        {/if}
        {#if props.dot !== undefined}
            <sup class="cm-badge-dot" style={styles}></sup>
        {/if}
    {:else}
        <span class={statusClass} style={statusStyle}></span>
        <span class="cm-badge-status-text">{props.text}</span>
    {/if}
</span>
